package gentle.Scheduler;

import com.alibaba.fastjson.JSONObject;
import gentle.GentleApplication;
import gentle.base.AliyunOssUtil;
import gentle.base.SqlMapper;
import gentle.base.StringUtil;
import gentle.entity.ExtenAccountInfo;
import gentle.exception.DateTimeKit;
import gentle.mapper.ReservationsDao;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
@Configuration
@EnableScheduling
public class Scheduler {
    @Autowired
    private ReservationsDao reservationsDao;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    AliyunOssUtil aliyunOssUtil;

    // 每天19:00 执行
    @Scheduled(cron = "0 10 23 * * ?")
    public void callin() {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginTime = simpleDateFormat.parse(DateTimeKit.now().substring(0, 10)+" 00:00:00");
            long beginTimes = beginTime.getTime() / 1000;//开始时间戳10位
            System.out.println("开始时间：" + beginTimes);
            Date endTime = simpleDateFormat.parse(DateTimeKit.now().substring(0, 10)+" 23:00:00");
            long endTimes = endTime.getTime() / 1000;//结束时间戳10位
            System.out.println("结束时间：" + endTimes);
            String managerid = "bj69635740";// {讯鸟为企业颁发的企业ID，为固定值}
            String passkey = "XAGdMpQC";//{讯鸟为企业颁发的passkey，为固定值 }
            long nowTime=System.currentTimeMillis()/ 1000;//当前时间戳10位
            //$str =$managerid.$passkey.$time;  //$str由三个字符串拼接而成，组成的字符串如此：
            String str=managerid+passkey+nowTime;
            String sign=shaEncode(str);//sha加密
            System.out.println("原始：" + str);
            System.out.println("SHA后：" + shaEncode(str));
            String result = "";
            String urlNameString = "http://openapi.infobird.com/v1/history/gethistory?" +
                    "managerid="+managerid+"&time="+nowTime+"&sign="+sign+"&isfz=0"+
                    "&beginTime="+beginTimes+"&endTime=" +endTimes+
                    "&callType=callin" ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if (result == null || "".equals(result)) {

            } else {
                String strStart="[{";
                int strStartIndex = result.indexOf("[{");
                int strEndIndex = result.indexOf("}]}");
                result = "{"+result.substring(strStartIndex, strEndIndex).substring(strStart.length())+"}";
                String[] aa = (result.substring(0, result.length() - 1).split("},"));
                if (aa.length > 0) {
                    for (String s : aa) {
                        s = s + "}";
                        System.out.println(s);
                        JSONObject jo = JSONObject.parseObject(new String(s));
                        String beginTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("beginTime"))) {
                            beginTime1="'"+jo.getString("beginTime")+"'";
                        }else{
                            beginTime1="null";
                        }
                        String endTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("endTime"))) {
                            endTime1="'"+jo.getString("endTime")+"'";
                        }else{
                            endTime1="null";
                        }
                        String AnswerCallTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("AnswerCallTime"))) {
                            AnswerCallTime1="'"+jo.getString("AnswerCallTime")+"'";
                        }else{
                            AnswerCallTime1="null";
                        }
                        String TransCallTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("TransCallTime"))) {
                            TransCallTime1="'"+jo.getString("TransCallTime")+"'";
                        }else{
                            TransCallTime1="null";
                        }
                        String AgentRingTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("AgentRingTime"))) {
                            AgentRingTime1="'"+jo.getString("AgentRingTime")+"'";
                        }else{
                            AgentRingTime1="null";
                        }
                        String OutDialTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("OutDialTime"))) {
                            OutDialTime1="'"+jo.getString("OutDialTime")+"'";
                        }else{
                            OutDialTime1="null";
                        }
                        String insql = "INSERT INTO `call_record_whxn` (`Id`, `invokeId`, `callerId`, `callId`, `presidePhoneNo`, `SubsidiariesSignNo`,`callDirection`," +
                                "`IsTransferred`, `TransInvokeId`, `beginTime`, `endTime`, `AnswerCallTime`, `TransCallTime`, `agentname`, `AgentRingTime`, `OutDialTime`, " +
                                "`UUIData`, `flag`, `IsAgentCall`) VALUES " +
                                " ('"+jo.getString("Id")+"', '"+jo.getString("invokeId")+"', '"+jo.getString("callerId")+"', '"+jo.getString("callId")+"', '"
                                +jo.getString("presidePhoneNo")+"', '"+jo.getString("SubsidiariesSignNo")+"', '"+jo.getString("callDirection")+"', '"
                                +jo.getString("IsTransferred")+"', '"+jo.getString("TransInvokeId")+"', "+beginTime1+", "+endTime1+", "
                                +AnswerCallTime1+", "+TransCallTime1+", '"+jo.getString("agentname")+"', "+AgentRingTime1+", "
                                +OutDialTime1+", '"+jo.getString("UUIData")+"', '"+jo.getString("flag")+"', '"+jo.getString("IsAgentCall")+"');";
                        sqlMapper.insert(insql);
                        callSite(managerid,nowTime,sign,beginTimes,endTimes,jo.getString("invokeId"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 每天19:00 执行
    @Scheduled(cron = "0 10 23 * * ?")
    public void callout() {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginTime = simpleDateFormat.parse(DateTimeKit.now().substring(0, 10)+" 00:00:00");
            long beginTimes = beginTime.getTime() / 1000;//开始时间戳10位
            System.out.println("开始时间：" + beginTimes);
            Date endTime = simpleDateFormat.parse(DateTimeKit.now().substring(0, 10)+" 23:00:00");
            long endTimes = endTime.getTime() / 1000;//结束时间戳10位
            System.out.println("结束时间：" + endTimes);
            String managerid = "bj69635740";// {讯鸟为企业颁发的企业ID，为固定值}
            String passkey = "XAGdMpQC";//{讯鸟为企业颁发的passkey，为固定值 }
            long nowTime=System.currentTimeMillis()/ 1000;//当前时间戳10位
            //$str =$managerid.$passkey.$time;  //$str由三个字符串拼接而成，组成的字符串如此：
            String str=managerid+passkey+nowTime;
            String sign=shaEncode(str);//sha加密
            System.out.println("原始：" + str);
            System.out.println("SHA后：" + shaEncode(str));
            String result = "";
            String urlNameString = "http://openapi.infobird.com/v1/history/gethistory?" +
                    "managerid="+managerid+"&time="+nowTime+"&sign="+sign+"&isfz=0"+
                    "&beginTime="+beginTimes+"&endTime=" +endTimes+
                    "&callType=callout" ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if (result == null || "".equals(result)) {

            } else {
                String strStart="[{";
                int strStartIndex = result.indexOf("[{");
                int strEndIndex = result.indexOf("}]}");
                result = "{"+result.substring(strStartIndex, strEndIndex).substring(strStart.length())+"}";
                String[] aa = (result.substring(0, result.length() - 1).split("},"));
                if (aa.length > 0) {
                    for (String s : aa) {
                        s = s + "}";
                        System.out.println(s);
                        JSONObject jo = JSONObject.parseObject(new String(s));
                        String beginTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("beginTime"))) {
                            beginTime1="'"+jo.getString("beginTime")+"'";
                        }else{
                            beginTime1="null";
                        }
                        String endTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("endTime"))) {
                            endTime1="'"+jo.getString("endTime")+"'";
                        }else{
                            endTime1="null";
                        }
                        String AnswerCallTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("AnswerCallTime"))) {
                            AnswerCallTime1="'"+jo.getString("AnswerCallTime")+"'";
                        }else{
                            AnswerCallTime1="null";
                        }
                        String TransCallTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("TransCallTime"))) {
                            TransCallTime1="'"+jo.getString("TransCallTime")+"'";
                        }else{
                            TransCallTime1="null";
                        }
                        String AgentRingTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("AgentRingTime"))) {
                            AgentRingTime1="'"+jo.getString("AgentRingTime")+"'";
                        }else{
                            AgentRingTime1="null";
                        }
                        String OutDialTime1="";
                        if (StringUtil.isNotEmpty(jo.getString("OutDialTime"))) {
                            OutDialTime1="'"+jo.getString("OutDialTime")+"'";
                        }else{
                            OutDialTime1="null";
                        }
                        String insql = "INSERT INTO `call_record_whxn` (`Id`, `invokeId`, `callerId`, `callId`, `presidePhoneNo`, `SubsidiariesSignNo`,`callDirection`," +
                                "`IsTransferred`, `TransInvokeId`, `beginTime`, `endTime`, `AnswerCallTime`, `TransCallTime`, `agentname`, `AgentRingTime`, `OutDialTime`, " +
                                "`UUIData`, `flag`, `IsAgentCall`) VALUES " +
                                " ('"+jo.getString("Id")+"', '"+jo.getString("invokeId")+"', '"+jo.getString("callerId")+"', '"+jo.getString("callId")+"', '"
                                +jo.getString("presidePhoneNo")+"', '"+jo.getString("SubsidiariesSignNo")+"', '"+jo.getString("callDirection")+"', '"
                                +jo.getString("IsTransferred")+"', '"+jo.getString("TransInvokeId")+"', "+beginTime1+", "+endTime1+", "
                                +AnswerCallTime1+", "+TransCallTime1+", '"+jo.getString("agentname")+"', "+AgentRingTime1+", "
                                +OutDialTime1+", '"+jo.getString("UUIData")+"', '"+jo.getString("flag")+"', '"+jo.getString("IsAgentCall")+"');";
                        sqlMapper.insert(insql);
                        callSite(managerid,nowTime,sign,beginTimes,endTimes,jo.getString("invokeId"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void callSite(String managerid,long nowTime,String sign,long beginTimes,long endTimes,String invokeId) {
        try {
            String result = "";
            String urlNameString = "http://openapi.infobird.com/v1/history/getrecurl?" +
                    "managerid="+managerid+"&time="+nowTime+"&sign="+sign+"&isfz=0"+
                    "&invokeid="+invokeId ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if (result == null || "".equals(result)) {

            } else {
                String[] aa = (result.substring(0, result.length() - 1).split("},"));
                if (aa.length > 0) {
                    for (String s : aa) {
                        s = (s + "}").replace("]", "").replace("[","");
                        System.out.println(s);
                        JSONObject jo = JSONObject.parseObject(new String(s));
                        String update = "update `call_record_whxn` " +
                                " set recordAddress='"+jo.getString("data")+"'" +
                                " where invokeId='"+invokeId+"'" ;
                        sqlMapper.update(update);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static MultipartFile getMulFileByPath(String picPath) {
        FileItem fileItem = createFileItem(picPath);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    private static FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = filePath.lastIndexOf(".");
        String extFile = filePath.substring(num);
        FileItem item = factory.createItem(textFieldName, "text/plain", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    public static String shaEncode(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

}
